package com.Lixiaoqian.PartyHistoryMuseum.ui;

import android.annotation.SuppressLint;
import android.content.pm.ApplicationInfo;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.WindowManager;
import android.webkit.WebView;

import com.Lixiaoqian.PartyHistoryMuseum.inface.ArchitectViewHolderInterface;
import com.Lixiaoqian.PartyHistoryMuseum.utils.Constant;
import com.Lixiaoqian.PartyHistoryMuseum.utils.PermissionsChecker;
import com.wikitude.architect.ArchitectView;
import com.wikitude.architect.ArchitectView.ArchitectUrlListener;
import com.wikitude.architect.ArchitectView.SensorAccuracyChangeListener;
import com.wikitude.architect.StartupConfiguration;

import java.io.IOException;

import butterknife.ButterKnife;
import butterknife.Unbinder;


/**
 * Abstract activity which handles live-cycle events.
 * Feel free to extend from this activity when setting up your own AR-Activity
 */
public abstract class AbstractArchitectCamActivity extends AppCompatActivity implements ArchitectViewHolderInterface {
    /**
     * holds the Wikitude SDK AR-View, this is where camera, markers, compass, 3D models etc. are rendered
     */
    public ArchitectView architectView;
    private String work_url = Constant.WIKITUDE_URL;
    /**
     * sensor accuracy listener in case you want to display calibration hints
     */
    protected SensorAccuracyChangeListener sensorAccuracyListener;

    /**
     * urlListener handling "document.location= 'architectsdk://...' " calls in JavaScript"
     */
    protected ArchitectUrlListener urlListener;
    public PermissionsChecker permissionChecker;
    private Unbinder bind;

    /**
     * Called when the activity is first created.
     */
    @SuppressLint("NewApi")
    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(getContentViewId());
        bind = ButterKnife.bind(this);
        permissionChecker=new PermissionsChecker(this);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//屏幕常亮
        initIntent();
        initButton();

		/*  
         *	this enables remote debugging of a WebView on Android 4.4+ when debugging = true in AndroidManifest.xml
		 *	If you get a compile time error here, ensure to have SDK 19+ used in your ADT/Eclipse.
		 *	You may even delete this block in case you don't need remote debugging or don't have an Android 4.4+ device in place.
		 *	Details: https://developers.google.com/chrome-developer-tools/docs/remote-debugging
		 */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (0 != (getApplicationInfo().flags &= ApplicationInfo.FLAG_DEBUGGABLE)) {
                WebView.setWebContentsDebuggingEnabled(true);
            }
        }
        /* set AR-view for life-cycle notifications etc. */

        initArchitechView();
    }


    protected void initArchitechView() {

        this.architectView = (ArchitectView) this.findViewById(this.getArchitectViewId());
        /* pass SDK key if you have one, this one is only valid for this package identifier and must not be used somewhere else */
        final StartupConfiguration config = new StartupConfiguration(this.getWikitudeSDKLicenseKey(), getFeatures(), this.getCameraPosition());
        //config.setCameraPosition(this.getCameraPosition());
        this.architectView.onCreate(config);
        // set accuracy listener if implemented, you may e.g. show calibration prompt for compass using this listener
        this.sensorAccuracyListener = this.getSensorAccuracyListener();
        // set urlListener, any calls made in JS like "document.location = 'architectsdk://foo?bar=123'" is forwarded to this listener, use this to interact between JS and native Android activity/fragment
        this.urlListener = this.getUrlListener();
        // register valid urlListener in architectView, ensure this is set before content is loaded to not miss any event
        if (this.urlListener != null && this.architectView != null) {
            this.architectView.registerUrlListener(this.getUrlListener());
        }
    }



       /* //高德定位
        aMapLocationListener=new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation location) {
                Log.i("location", "onLocationChanged: "+location.getLongitude());
                if (location != null) {
                    // sore last location as member, in case it is needed somewhere (in e.g. your adjusted project)
                    if (AbstractArchitectCamActivity.this.architectView != null) {
                        // check if location has altitude at certain accuracy level & call right architect method (the one with altitude information)
                        if (location.hasAltitude() && location.getAccuracy() < 7) {
                            AbstractArchitectCamActivity.this.architectView.setLocation(location.getLatitude(), location.getLongitude(), location.getAltitude(), location.getAccuracy());
                        } else {
                            AbstractArchitectCamActivity.this.architectView.setLocation(location.getLatitude(), location.getLongitude(), location.getAccuracy());
                        }
                    }
                }else{
                    ToastUtils.showShort(App.getContext(),"定位失败");
                }
            }
        };*/
        // locationProvider used to fetch user position



    protected abstract StartupConfiguration.CameraPosition getCameraPosition();

    private int getFeatures() {
        int features = (false ? StartupConfiguration.Features.Geo : 0) | (true ? StartupConfiguration.Features.Tracking2D : 0);
        return features;
    }

    @Override
    protected void onPostCreate(final Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        lodingWorld();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (this.architectView != null) {
            this.architectView.onResume();
            if (this.sensorAccuracyListener != null) {
                this.architectView.registerSensorAccuracyChangeListener(this.sensorAccuracyListener);
            }
        }
    }

    /**
     * 加载AR世界
     */
    private void lodingWorld() {
        if (this.architectView != null&&work_url!=null) {
            this.architectView.onPostCreate();
            try {
                this.architectView.load(work_url);
                if (this.getInitialCullingDistanceMeters() != ArchitectViewHolderInterface.CULLING_DISTANCE_DEFAULT_METERS) {
                    this.architectView.setCullingDistance(this.getInitialCullingDistanceMeters());
                }
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        onArViewPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        onDestoryArView();
        if (bind!=null){
            bind.unbind();
        }

    }

    protected void onDestoryArView() {
        // call mandatory live-cycle method of architectVie
        if (this.architectView != null) {
            this.architectView.onDestroy();
            this.architectView=null;
        }

    }

    /**
     * 生命周期暂停
     */
    private void onArViewPause() {
        if (this.architectView != null) {
            this.architectView.onPause();
            // unregister accuracy listener in architectView, if set
            if (this.sensorAccuracyListener != null) {
                this.architectView.unregisterSensorAccuracyChangeListener(this.sensorAccuracyListener);
            }
        }
    }


    /**
     * 切换场景，重新加载url
     */
    public void reLoadUrl(String rePath) {
        if (this.architectView != null) {
            try {
                this.architectView.load(rePath);
                work_url = rePath;
                if (this.getInitialCullingDistanceMeters() != ArchitectViewHolderInterface.CULLING_DISTANCE_DEFAULT_METERS) {
                    this.architectView.setCullingDistance(this.getInitialCullingDistanceMeters());
                }
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    /**
     * 重置，先销毁界面，再重新加载
     */
    public void onReset() {
        this.architectView.callJavascript("World.init()");
    }


    /**
     * 视频下载完成
     */
    public void downFileFinish() {
        this.architectView.callJavascript("Interface.onVideoDownloaded()");
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        if (this.architectView != null) {
            this.architectView.onLowMemory();
        }
    }

    /**
     * call JacaScript in architectView
     * @param methodName
     * @param arguments
     */
    public void callJavaScript(final String methodName, final String[] arguments) {
        final StringBuilder argumentsString = new StringBuilder("");
        for (int i= 0; i<arguments.length; i++) {
            argumentsString.append(arguments[i]);
            if (i<arguments.length-1) {
                argumentsString.append(", ");
            }
        }

        if (this.architectView!=null) {
            final String js = ( methodName + "( " + argumentsString.toString() + " );" );
            this.architectView.callJavascript(js);
        }
    }
    /**
     * url listener fired once e.g. 'document.location = "architectsdk://foo?bar=123"' is called in JS
     *
     * @return
     */
    @Override
    public abstract ArchitectUrlListener getUrlListener();



    /**
     * @return Wikitude SDK license key, checkout www.wikitude.com for details
     */
    @Override
    public abstract String getWikitudeSDKLicenseKey();

    /**
     * @return layout-id of architectView, e.g. R.id.architectView
     */
    @Override
    public abstract int getArchitectViewId();


    /**
     * @return Implementation of Sensor-Accuracy-Listener. That way you can e.g. show prompt to calibrate compass
     */
    @Override
    public abstract ArchitectView.SensorAccuracyChangeListener getSensorAccuracyListener();


    public abstract void initIntent();

    public abstract void initButton();

}